package com.xyy.kingdeejdy.utils.jdy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smecloud.apigw.client.ApigwClient;
import com.smecloud.apigw.constant.HttpMethod;
import com.smecloud.apigw.model.ApiRequest;
import com.smecloud.apigw.model.ApiResult;
import com.smecloud.apigw.util.SHAUtil;
import com.xyy.kingdeejdy.pojo.erp.help.JdyApp;
import com.xyy.kingdeejdy.pojo.erp.help.JdyAuthorize;
import com.xyy.kingdeejdy.pojo.erp.help.ResultPo;
import com.xyy.kingdeejdy.pojo.erp.help.ResultToken;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccessToken {
    private static String token;

    public static String get() {
        if (token != null && !token.isEmpty()) {
            return token;
        }
        ApiRequest request = new ApiRequest(HttpMethod.POST_FORM, "api.kingdee.com", "/jdyconnector/app_management/push_app_authorize");
        Map<String, String> maps = new HashMap<>();
        maps.put("outerInstanceId", "107980925391998976");
        request.setFormParam(maps);
        request.setBodyJson(JSONObject.toJSONString("").getBytes());
        ApiResult result = ApigwClient.getInstance().send(request);
        JdyAuthorize jdyAuthorize = JSON.parseObject(result.getBody(), JdyAuthorize.class);
        List<JdyApp> data = jdyAuthorize.getData();
        JdyApp jdyApp = data.get(0);
        ApiRequest apiRequest = new ApiRequest(HttpMethod.GET, "api.kingdee.com", "/jdyconnector/app_management/kingdee_auth_token");
        String appKey = jdyApp.getAppKey();
        String appSecret = jdyApp.getAppSecret();
        Map<String, String> map = new HashMap<>();
        map.put("app_key", appKey);
        String appSignature = SHAUtil.SHA256HMAC(appKey, appSecret);
        appSignature = Base64.getEncoder().encodeToString(appSignature.getBytes());
        map.put("app_signature", appSignature);
        apiRequest.setQuerys(map);
        apiRequest.setBodyJson(JSONObject.toJSONString("").getBytes());
        ApiResult send = ApigwClient.getInstance().send(apiRequest);
        ResultPo resultPo = JSON.parseObject(send.getBody(), ResultPo.class);
        ResultToken datas = JSON.parseObject(JSON.toJSONString(resultPo.getData()), ResultToken.class);
        token = datas.getAccessToken();
        return token;
    }

}
